package cn.cosmosx.base.handler;

import cn.cosmosx.base.define.ResultVO;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * controller响应结果统一处理
 *
 * @author gengzhy
 */
@Slf4j
@RestControllerAdvice
public class ResponseBodyHandler implements ResponseBodyAdvice<Object> {
    @Autowired
    private Gson gson;
    /**
     * 判断是否要交给 beforeBodyWrite 方法执行，ture：需要；false：不需要
     *
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除swagger请求（指定了包路径，该判断可略去）
        return !isSwaggerResponse(returnType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return ResultVO.success();
        }
        if (body instanceof ResultVO) {
            return body;
        }
        // 如果响应结果是String类型，则使用的转换器是StringHttpMessageConverter，
        // 不能将对象ResultVO直接转换为String，需要转换为JSON字符串
        if (body instanceof String) {
            return gson.toJson(ResultVO.success(body));
        }
        return ResultVO.success(body);
    }

    /**
     * 是否是swagger响应
     *
     * @param returnType
     * @return
     */
    boolean isSwaggerResponse(MethodParameter returnType) {
        String typeName = returnType.getMember().getDeclaringClass().getTypeName();
        return typeName.contains("springfox") || typeName.contains("swagger");
    }
}
